package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserDao;
import dao.Factoty.DaoFactory;
import domain.User;
import service.Factory.ServiceFactory;

/**
 * Servlet implementation class UserInfoServlet
 */
@WebServlet("/UserInfoServlet")
public class UserInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User curUser = (User)session.getAttribute("_user");

		if (curUser != null) {
			try {
				User user = ServiceFactory.getUserServiceInstance().findUserById(curUser.getId());
				
				request.setAttribute("user", user);
				
				request.getRequestDispatcher("/client/UserInfo.jsp").forward(request, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				response.sendRedirect(request.getContextPath()+ "/HomeServlet");
			}
		} else {
			response.sendRedirect(request.getContextPath()+ "/HomeServlet");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		User curUser = (User)session.getAttribute("_user");
		
		if (curUser != null) {
			String username = request.getParameter("username");
			String gender = request.getParameter("gender");
			String email = request.getParameter("email");
			String telephone = request.getParameter("telephone");
			String introduce = request.getParameter("introduce");
			User user = new User();
			
			user.setId(curUser.getId());
			user.setUsername(username);
			user.setGender(gender);
			user.setEmail(email);
			user.setTelephone(telephone);
			user.setIntroduce(introduce);
			
			try {
				ServiceFactory.getUserServiceInstance().updateUser(user);
				session.setAttribute("_username", user.getUsername());
				response.sendRedirect(request.getContextPath()+ "/UserInfoServlet");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				doGet(request, response);
			}
		} else {
			doGet(request, response);
		}
	}

}
